<?php
class PlayerSalary {
  const TOTAL_XPATH = "./total[1]";
  const SKILL_XPATH = "./skill[1]";
  const TRANSFER_XPATH = "./transfer[1]";
  const PERFORMANCE_XPATH = "./performance[1]";
  const LOYALTY_XPATH = "./loyalty[1]";

  private $total;

  private $db;

  public function __construct($database) {
    $this->db = $database;

    $this->total = 0;
  }

  public function loadFromNode(DOMElement $docNode) {
    $doc = $docNode->ownerDocument;

    $xPath = new DOMXPath($doc);

    $qResult = $xPath->query(PlayerSalary::TOTAL_XPATH,$docNode);
    $this->total = $qResult->item(0)->nodeValue;
  }

  public function toXHTML() {
    $xhtml = "Total: {$this->total}";

    return $xhtml;
  }

  public function insertNewToDB($playerId) {
    $this->db->set('playerId',$playerId);
    $this->db->set('total',$this->total);

    $query = $this->db->insert('playersalary');

    if (!$query) {
      log_message('error', 'Error during playerage inserttion!');
      return false;
    }

    return $this->db->insert_id();
  }

  public function amendOldInDB($id) {
    $this->db->where('id',$id);
    $query = $this->db->get('playersalary');

    if (!$query) {
      log_message('error','Error during playersalary amendment!');
    } else {
      $tRow = $query->row();
      $oldId = $tRow->id;
      $playerId = $tRow->playerId;

      if ($tRow->total!=$this->total) {
        $newId = $this->insertNewToDB($playerId);

        $this->db->set('playerId', $playerId);
        $this->db->set('table','playersalary');
        $this->db->set('oldId',$oldId);
        $this->db->set('newId',$newId);
        $this->db->set('insertTime',date('Y-m-d H:i:s'));
        $query = $this->db->insert('playerhistory');

        if (!$query) {
          log_message('error','Playersalary amend was unsuccesful!');
        } else {
          return $newId;
        }
      }
    }
    return $oldId;
  }

  public function loadFromDB($salaryId) {
    $this->db->where('id',$salaryId);
    $query = $this->db->get('playersalary');

    if (!$query || $query->num_rows()==0) {
      log_message('error', 'PlayerSalary ('.$salaryId.') not found in the database!');
    } else {
      $result = $query->row();

      $this->total = $result->total;
    }
  }
}
?>
